package com.shen.nettysocketchat

import android.util.Log
import com.shen.nettysocketchat.bean.AppMessage
import com.shen.nettysocketchat.bean.BaseMessage
import com.shen.nettysocketchat.bean.ContentMessage
import com.shen.nettysocketchat.handler.IMessageHandler
import com.shen.nettysocketchat.handler.MessageHandlerFactory
import com.shen.nettysocketchat.utils.CThreadPoolExecutor
import java.lang.Exception

/**
 * 消息处理器
 */
class MessageProcessor private constructor() : IMessageProcessor {

    companion object {
        private val TAG = MessageProcessor::class.java.simpleName
        val instance: IMessageProcessor
            get() = MessageProcessor()
    }


    /**
     * 接收消息
     * @param message
     */
     override fun receiveMsg(message: AppMessage?) {
        CThreadPoolExecutor.runInBackground(Runnable {
            try {
                val messageHandler: IMessageHandler? =
                    MessageHandlerFactory.getHandlerByMsgType(message?.head?.msgType ?: -1)

                if (messageHandler != null) {
                    messageHandler.execute(message)
                } else {
                    Log.e(TAG, "未找到消息处理handler，msgType=" + message?.head?.msgType)
                }
            } catch (e: Exception) {
                Log.e(TAG, "消息处理出错，reason=" + e.message)
            }
        })
    }

    /**
     * 发送消息
     *
     * @param message
     */
    override fun sendMsg(message: AppMessage?) {
        CThreadPoolExecutor.runInBackground(Runnable {
            val isActive = IMSClientBootstrap.instance.isActive
            if (isActive && message != null) {
                IMSClientBootstrap.instance.sendMessage(
                    MessageBuilder.getProtoBufMessageBuilderByAppMessage(message).build()
                )
            } else {
                Log.e(TAG, "发送消息失败")
            }
        })
    }

    /**
     * 发送消息
     *
     * @param message
     */
    override fun sendMsg(message: ContentMessage?) {
        if(message != null)
            this.sendMsg(MessageBuilder.buildAppMessage(message))
    }

    /**
     * 发送消息
     *
     * @param message
     */
    override fun sendMsg(message: BaseMessage?) {
        if(message != null)
            this.sendMsg(MessageBuilder.buildAppMessage(message))
    }

}